from django.contrib import admin

from meet.models import PointsRule


# Register your models here.
# 可以在Django admin中或通过管理命令添加
def init_points_rules():
    """初始化积分规则"""
    rules = [
        {
            'name': '参加活动',
            'action': 'activity_join',
            'points': 10,
            'daily_limit': 5,
            'description': '成功报名一个活动获得10积分，每日最多获得50积分'
        },
        {
            'name': '活动评价',
            'action': 'activity_review',
            'points': 5,
            'daily_limit': 10,
            'description': '对参加的活动进行评价获得5积分，每日最多获得50积分'
        },
        {
            'name': '发布讨论',
            'action': 'discussion_post',
            'points': 3,
            'daily_limit': 5,
            'description': '在讨论区发布帖子获得3积分，每日最多获得15积分'
        },
        {
            'name': '评论讨论',
            'action': 'discussion_comment',
            'points': 1,
            'daily_limit': 20,
            'description': '在讨论区发表评论获得1积分，每日最多获得20积分'
        },
        {
            'name': '邀请好友',
            'action': 'invite_friend',
            'points': 50,
            'daily_limit': 0,
            'description': '成功邀请好友注册获得50积分'
        },
        {
            'name': '每日签到',
            'action': 'daily_signin',
            'points': 5,  # 每日签到基础积分
            'daily_limit': 1,  # 每天只能签到一次
            'description': '每日签到获得5积分，连续签到7天额外奖励5积分'
        },

    ]

    for rule_data in rules:
        PointsRule.objects.get_or_create(
            action=rule_data['action'],
            defaults=rule_data
        )





################################
from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.contrib import messages

from meet.models import (
    PointsRule, PointsProduct, PointsExchange, PointsHistory,
    DailySignIn
)


# 积分商品管理
@admin.register(PointsProduct)
class PointsProductAdmin(admin.ModelAdmin):
    list_display = [
        'name', 'category', 'points_required', 'stock',
        'exchange_count', 'status', 'created_at', 'product_image_preview'
    ]
    list_filter = ['category', 'status', 'created_at']
    search_fields = ['name', 'description']
    list_editable = ['stock', 'status', 'points_required']
    readonly_fields = ['exchange_count', 'created_at', 'updated_at', 'product_image_preview']
    fieldsets = [
        ('基本信息', {
            'fields': [
                'name', 'description', 'category', 'image', 'product_image_preview'
            ]
        }),
        ('价格与库存', {
            'fields': [
                'points_required', 'original_price', 'stock', 'exchange_count'
            ]
        }),
        ('状态与排序', {
            'fields': [
                'status', 'sort_order'
            ]
        }),
        ('时间信息', {
            'fields': [
                'created_at', 'updated_at'
            ]
        }),
    ]

    def product_image_preview(self, obj):
        if obj.image:
            return format_html('<img src="{}" style="max-height: 100px; max-width: 100px;" />', obj.image.url)
        return "无图片"

    product_image_preview.short_description = '图片预览'

    actions = ['activate_products', 'deactivate_products', 'restock_products']

    def activate_products(self, request, queryset):
        updated = queryset.update(status='active')
        self.message_user(request, f'成功上架 {updated} 个商品')

    activate_products.short_description = "上架选中商品"

    def deactivate_products(self, request, queryset):
        updated = queryset.update(status='inactive')
        self.message_user(request, f'成功下架 {updated} 个商品')

    deactivate_products.short_description = "下架选中商品"

    def restock_products(self, request, queryset):
        restock_amount = 10  # 默认补货数量
        for product in queryset:
            product.stock += restock_amount
            product.save()
        self.message_user(request, f'成功为 {queryset.count()} 个商品补货')

    restock_products.short_description = "补货选中商品(每个+10)"


# 积分兑换管理
@admin.register(PointsExchange)
class PointsExchangeAdmin(admin.ModelAdmin):
    list_display = [
        'id', 'user_info', 'product_info', 'points_used',
        'status_badge', 'exchange_code', 'created_at', 'action_buttons'
    ]
    list_filter = ['status', 'product__category', 'created_at']
    search_fields = [
        'user__username', 'user__email',
        'product__name', 'exchange_code'
    ]
    readonly_fields = ['created_at', 'updated_at', 'exchange_code']
    list_per_page = 20

    fieldsets = [
        ('兑换信息', {
            'fields': [
                'user', 'product', 'points_used', 'status'
            ]
        }),
        ('收货信息', {
            'fields': [
                'shipping_address', 'contact_name', 'contact_phone'
            ]
        }),
        ('物流信息', {
            'fields': [
                'tracking_number', 'exchange_code'
            ]
        }),
        ('时间信息', {
            'fields': [
                'created_at', 'updated_at'
            ]
        }),
    ]

    def user_info(self, obj):
        url = reverse('admin:user_user_change', args=[obj.user.id])
        return format_html('<a href="{}">{}</a>', url, obj.user.username)

    user_info.short_description = '用户'

    def product_info(self, obj):
        url = reverse('admin:meet_pointsproduct_change', args=[obj.product.id])
        return format_html('<a href="{}">{}</a>', url, obj.product.name)

    product_info.short_description = '商品'

    def status_badge(self, obj):
        status_colors = {
            'pending': 'orange',
            'shipped': 'blue',
            'completed': 'green',
            'cancelled': 'red'
        }
        color = status_colors.get(obj.status, 'gray')
        return format_html(
            '<span style="background-color: {}; color: white; padding: 2px 8px; border-radius: 10px; font-size: 12px;">{}</span>',
            color, obj.get_status_display()
        )

    status_badge.short_description = '状态'

    def action_buttons(self, obj):
        buttons = []
        if obj.status == 'pending':
            buttons.append(
                f'<a href="/admin/meet/pointsexchange/{obj.id}/ship/" class="button" style="background-color: #007bff; color: white; padding: 5px 10px; text-decoration: none; border-radius: 3px; margin-right: 5px;">发货</a>'
            )
            buttons.append(
                f'<a href="/admin/meet/pointsexchange/{obj.id}/cancel/" class="button" style="background-color: #dc3545; color: white; padding: 5px 10px; text-decoration: none; border-radius: 3px;">取消</a>'
            )
        elif obj.status == 'shipped':
            buttons.append(
                f'<a href="/admin/meet/pointsexchange/{obj.id}/complete/" class="button" style="background-color: #28a745; color: white; padding: 5px 10px; text-decoration: none; border-radius: 3px;">完成</a>'
            )
        return format_html(' '.join(buttons)) if buttons else '-'

    action_buttons.short_description = '操作'

    actions = ['mark_as_shipped', 'mark_as_completed', 'cancel_exchanges']

    def mark_as_shipped(self, request, queryset):
        updated = queryset.filter(status='pending').update(status='shipped')
        self.message_user(request, f'成功标记 {updated} 个订单为已发货')

    mark_as_shipped.short_description = "标记为已发货"

    def mark_as_completed(self, request, queryset):
        updated = queryset.filter(status='shipped').update(status='completed')
        self.message_user(request, f'成功标记 {updated} 个订单为已完成')

    mark_as_completed.short_description = "标记为已完成"

    def cancel_exchanges(self, request, queryset):
        updated = queryset.filter(status__in=['pending', 'shipped']).update(status='cancelled')
        self.message_user(request, f'成功取消 {updated} 个订单')

    cancel_exchanges.short_description = "取消选中订单"


# 积分历史管理
@admin.register(PointsHistory)
class PointsHistoryAdmin(admin.ModelAdmin):
    list_display = ['user', 'points_display', 'source_type_display', 'description', 'created_at']
    list_filter = ['source_type', 'created_at']
    search_fields = ['user__username', 'description']
    readonly_fields = ['created_at']
    list_per_page = 50
    actions = ['adjust_points']

    def points_display(self, obj):
        color = 'green' if obj.points > 0 else 'red'
        sign = '+' if obj.points > 0 else ''
        return format_html(
            '<span style="color: {}; font-weight: bold;">{}{}</span>',
            color, sign, obj.points
        )

    points_display.short_description = '积分变化'

    def source_type_display(self, obj):
        return obj.get_source_type_display()

    source_type_display.short_description = '来源类型'

    def adjust_points(self, request, queryset):
        # 这里可以添加积分调整的逻辑
        # 例如弹出一个表单让管理员输入调整的积分值
        pass

    adjust_points.short_description = "调整选中用户的积分"



# 每日签到管理
@admin.register(DailySignIn)
class DailySignInAdmin(admin.ModelAdmin):
    list_display = ['user', 'signin_date', 'consecutive_days', 'points_earned', 'created_at']
    list_filter = ['signin_date', 'created_at']
    search_fields = ['user__username']
    readonly_fields = ['created_at']
    date_hierarchy = 'signin_date'


# 积分规则管理
@admin.register(PointsRule)
class PointsRuleAdmin(admin.ModelAdmin):
    list_display = ['name', 'action', 'points', 'daily_limit', 'is_active', 'created_at']
    list_filter = ['is_active', 'created_at']
    list_editable = ['points', 'daily_limit', 'is_active']

    actions = ['activate_rules', 'deactivate_rules']

    def activate_rules(self, request, queryset):
        updated = queryset.update(is_active=True)
        self.message_user(request, f'成功启用 {updated} 条规则')

    activate_rules.short_description = "启用选中规则"

    def deactivate_rules(self, request, queryset):
        updated = queryset.update(is_active=False)
        self.message_user(request, f'成功禁用 {updated} 条规则')

    deactivate_rules.short_description = "禁用选中规则"


# 自定义管理动作的视图
from django.shortcuts import get_object_or_404
from django.contrib.admin.views.decorators import staff_member_required


@staff_member_required
def mark_shipped(request, exchange_id):
    try:
        exchange = PointsExchange.objects.get(id=exchange_id)
        if exchange.status == 'pending':
            exchange.status = 'shipped'
            exchange.save()
            messages.success(request, f'订单 #{exchange_id} 已标记为已发货')
        else:
            messages.error(request, '只能对待处理订单进行发货操作')
    except PointsExchange.DoesNotExist:
        messages.error(request, '订单不存在')

    return HttpResponseRedirect(reverse('admin:meet_pointsexchange_changelist'))


@staff_member_required
def mark_completed(request, exchange_id):
    try:
        exchange = PointsExchange.objects.get(id=exchange_id)
        if exchange.status == 'shipped':
            exchange.status = 'completed'
            exchange.save()
            messages.success(request, f'订单 #{exchange_id} 已标记为已完成')
        else:
            messages.error(request, '只能对已发货订单进行完成操作')
    except PointsExchange.DoesNotExist:
        messages.error(request, '订单不存在')

    return HttpResponseRedirect(reverse('admin:meet_pointsexchange_changelist'))


@staff_member_required
def cancel_exchange(request, exchange_id):
    try:
        exchange = PointsExchange.objects.get(id=exchange_id)
        if exchange.status in ['pending', 'shipped']:
            exchange.status = 'cancelled'
            exchange.save()
            messages.success(request, f'订单 #{exchange_id} 已取消')
        else:
            messages.error(request, '只能取消待处理或已发货的订单')
    except PointsExchange.DoesNotExist:
        messages.error(request, '订单不存在')

    return HttpResponseRedirect(reverse('admin:meet_pointsexchange_changelist'))


# 初始化积分规则
def init_points_rules():
    """初始化积分规则"""
    rules = [
        {
            'name': '参加活动',
            'action': 'activity_join',
            'points': 10,
            'daily_limit': 5,
            'description': '成功报名一个活动获得10积分，每日最多获得50积分'
        },
        {
            'name': '活动评价',
            'action': 'activity_review',
            'points': 5,
            'daily_limit': 10,
            'description': '对参加的活动进行评价获得5积分，每日最多获得50积分'
        },
        {
            'name': '发布讨论',
            'action': 'discussion_post',
            'points': 3,
            'daily_limit': 5,
            'description': '在讨论区发布帖子获得3积分，每日最多获得15积分'
        },
        {
            'name': '评论讨论',
            'action': 'discussion_comment',
            'points': 1,
            'daily_limit': 20,
            'description': '在讨论区发表评论获得1积分，每日最多获得20积分'
        },
        {
            'name': '邀请好友',
            'action': 'invite_friend',
            'points': 50,
            'daily_limit': 0,
            'description': '成功邀请好友注册获得50积分'
        },
        {
            'name': '每日签到',
            'action': 'daily_signin',
            'points': 5,
            'daily_limit': 1,
            'description': '每日签到获得5积分，连续签到7天额外奖励5积分'
        },
    ]

    for rule_data in rules:
        PointsRule.objects.get_or_create(
            action=rule_data['action'],
            defaults=rule_data
        )


# 应用启动时初始化积分规则
init_points_rules()


# 添加积分调整视图
@staff_member_required
def adjust_user_points(request, user_id):
    """调整用户积分"""
    if request.method == 'POST':
        try:
            user = User.objects.get(id=user_id)
            points = int(request.POST.get('points', 0))
            reason = request.POST.get('reason', '管理员调整')

            # 更新用户积分
            user.points += points
            user.save()

            # 记录积分历史
            PointsHistory.objects.create(
                user=user,
                points=points,
                source_type='admin_adjust',
                description=f'管理员调整: {reason}'
            )

            messages.success(request, f'成功为用户 {user.username} 调整 {points} 积分')
            return redirect('admin:user_user_change', user_id)

        except User.DoesNotExist:
            messages.error(request, '用户不存在')
        except Exception as e:
            messages.error(request, f'调整失败: {str(e)}')

    return redirect('admin:user_user_changelist')


# user/admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.utils.html import format_html
from django.contrib import messages
from user.models import User, PasswordResetCode, UserProfile


# 自定义 UserAdmin
class UserAdmin(BaseUserAdmin):
    list_display = ['username', 'email', 'phone', 'points', 'is_active', 'is_staff', 'date_joined']
    list_filter = ['is_active', 'is_staff', 'date_joined']
    search_fields = ['username', 'email', 'phone']
    actions = ['add_points_action', 'deduct_points_action', 'reset_points_action']

    fieldsets = BaseUserAdmin.fieldsets + (
        ('积分信息', {
            'fields': ('points',)
        }),
        ('其他信息', {
            'fields': ('phone', 'bio', 'interests', 'avatar')
        }),
    )

    def add_points_action(self, request, queryset):
        """为选中用户增加积分"""
        points_to_add = 100  # 默认增加100积分
        for user in queryset:
            user.points += points_to_add
            user.save()
        self.message_user(request, f"成功为 {queryset.count()} 个用户增加{points_to_add}积分")

    add_points_action.short_description = "为选中用户增加100积分"

    def deduct_points_action(self, request, queryset):
        """为选中用户扣除积分"""
        points_to_deduct = 100  # 默认扣除100积分
        for user in queryset:
            if user.points >= points_to_deduct:
                user.points -= points_to_deduct
                user.save()
        self.message_user(request, f"成功为 {queryset.count()} 个用户扣除{points_to_deduct}积分")

    deduct_points_action.short_description = "为选中用户扣除100积分"

    def reset_points_action(self, request, queryset):
        """重置选中用户的积分"""
        for user in queryset:
            user.points = 0
            user.save()
        self.message_user(request, f"成功重置 {queryset.count()} 个用户的积分")

    reset_points_action.short_description = "重置选中用户的积分为0"


# 注册 User 模型
admin.site.register(User, UserAdmin)


@admin.register(PasswordResetCode)
class PasswordResetCodeAdmin(admin.ModelAdmin):
    list_display = ['email', 'code', 'is_used', 'created_at']
    list_filter = ['is_used', 'created_at']
    search_fields = ['email', 'code']
    readonly_fields = ['created_at']

@admin.register(UserProfile)
class UserProfileAdmin(admin.ModelAdmin):
    list_display = ['user', 'gender', 'birthday', 'location']
    list_filter = ['gender']
    search_fields = ['user__username', 'location']











#############################
# meet/admin.py 中添加以下代码

from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from user.models import User
from meet.models import PointsHistory


@staff_member_required
def adjust_user_points(request, user_id):
    """调整用户积分页面"""
    user = get_object_or_404(User, id=user_id)

    if request.method == 'POST':
        try:
            points = int(request.POST.get('points', 0))
            reason = request.POST.get('reason', '管理员调整')
            action = request.POST.get('action', 'add')  # add 或 set

            old_points = user.points

            if action == 'add':
                user.points += points
                change_type = '增加'
            else:  # set
                user.points = points
                change_type = '设置'

            user.save()

            # 记录积分历史
            PointsHistory.objects.create(
                user=user,
                points=points if action == 'add' else (points - old_points),
                source_type='admin_adjust',
                description=f'管理员{change_type}积分: {reason}'
            )

            messages.success(request, f'成功为用户 {user.username} {change_type}积分：{points} → 当前积分：{user.points}')
            return redirect('admin:user_user_change', user_id)

        except ValueError:
            messages.error(request, '请输入有效的积分数值')
        except Exception as e:
            messages.error(request, f'调整失败: {str(e)}')

    # 显示调整表单
    context = {
        'user': user,
        'title': f'调整用户积分 - {user.username}'
    }
    return render(request, 'admin/adjust_points.html', context)

# 在 UserAdmin 中添加自定义按钮（在 user/admin.py 中已经处理）